<template>
	<view class="page">
		<!-- 课程概览 -->
		<view class="course-overview">
			<view class="overview-left">
				<text class="course-title">{{category.categoryName}}</text>
				<text class="course-desc">总时长: --小时 | 评分: -- | 最新版: v3.0</text>
			</view>
			<view class="overview-right">
				<!-- <image class="ai-icon" :src="aiIconUrl" mode="aspectFill" /> -->
			</view>
		</view>
		<view class="price-button">
			<text class="price-text" :class="isAllCoursesPurchased ? 'purchased' : ''"
				@click="isAllCoursesPurchased ? null : toOrder(treeData.totalPrice, category.categoryName, treeData)">
				{{isAllCoursesPurchased ? '您已经购买过此专业课程' : '购买此专业 (' + treeData.totalPrice + '元)'}}
			</text>
		</view>
		<!-- 课程列表 -->
		<scroll-view class="course-list" scroll-y>
			<view class="course-section" v-for="(section, index) in treeData.children" :key="index">
				<view class="section-header">
					<text class="section-title">{{ section.title }}</text>
					<text class="section-info">共计: {{ section.children.length }}门课</text>
				</view>
				<view class="section-price" :class="isSectionPurchased(section) ? 'purchased' : ''"
					@click="isSectionPurchased(section) ? null : toOrder(section.totalPrice, section.title, section)">
					<text class="price-label">
						{{isSectionPurchased(section) ? '您已购买本阶段' : '购买此阶段 (' + section.totalPrice + '元)'}}
					</text>
				</view>

				<view class="course-cards">
					<view v-for="(course, cIndex) in section.children" :key="cIndex">
						<view class="course-card" @tap="toDeatl(course)">
							<view class="card-left">
								<img class="ai-icon"
									src="https://ai-public.mastergo.com/ai/img_res/e0ab13f7a22863423628cc0c4a7b3ade.jpg"
									draggable="false">
							</view>
							<view class="card-right">
								<text class="card-title">{{ course.title }}</text>
								<text class="card-desc">课程描述</text>
								<view class="card-stats">
									<view class="views">
										<uni-icons type="eye" size="14" color="#666666" />
										<text class="view-count">----次观看</text>
									</view>
									<text v-if="course.price" class="course-price">{{ course.totalPrice }}</text>
									<view v-for="item in course.children">
										<text class="view-count">{{item.title}}</text>
										<text class="view-count">{{item.price}}</text>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		<view class="pay-container" v-show="ifclick">
			<view class="pay-mask" @click="closeOrder"></view>
			<view class="pay-content">
				<view class="pay-title">结算台</view>
				<view class="pay-notice">该课程是付费课程，您需要先按实际授课才能使用相关内容</view>
				<view class="pay-info">
					<uni-text class="info-name">{{pagcontent.name}}</uni-text>
					<uni-text class="info-price">{{pagcontent.moneny}}元</uni-text>
				</view>
				<view class="pay-actions">
					<uni-button class="action-btn alipay" @click="handleAlipay">支付宝支付</uni-button>
				</view>
				<view class="pay-tips">
					小小提示 提示词暂未想好 这里采用沙盒支付
				</view>
			</view>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import { onLoad } from '@dcloudio/uni-app'
	import { onMounted, ref, computed } from 'vue';
	import { getChapterById } from '@/pages/utils/api/clazz.js'
	import { createOrder } from '@/pages/utils/api/order';
    import { onBackPress } from '@dcloudio/uni-app'
	import { navigateToLogin, navigateTo } from '@/components/navigateTo.js'

	const errorMessage = ref('');
	import { useUserStore } from '@/stores/api.js'
	const userStore = useUserStore();
	const aiIconUrl = 'https://ai-public.mastergo.com/ai/img_res/9c2cda92479b7dc926ab707cb410b836.jpg';
	const treeData = ref([]);
	let paymentAmount = "";
	const pagcontent = ref({
		moneny: "",
		name: ''
	})
	const ifclick = ref(false);
	let category = {};
	let userInfo = {};

	// 检查是否拥有指定课程ID数组中的所有课程
	// const hasAllCourses = (courseIds: number[]) => {
	//   if (!userHaveCourseId.value || userHaveCourseId.value.length === 0) return false;

	//   return courseIds.every(id => userHaveCourseId.value.includes(id));
	// }
	function hasAllCourses(courseIds : number[]) : boolean {
		if (!userHaveCourseId.value || userHaveCourseId.value.length === 0) {
			return false;
		}

		return courseIds.every(function (id) {
			return userHaveCourseId.value.includes(id);
		});
	}
    onBackPress(() => {
      // 这里可以添加你的逻辑判断
      uni.switchTab({
        url: '/pages/main/index' // 指定要跳转的页面路径
      })
      return true // 拦截默认返回行为
    })
	// 检查某个阶段是否已全部购买
	const isSectionPurchased = (section : any) => {
		if (!section.children || section.children.length === 0) return false;

		const courseIds = section.children.map(course => course.courseId);
		return hasAllCourses(courseIds);
	}

	// 检查整个专业是否已全部购买
	const isAllCoursesPurchased = computed(() => {
		if (!treeData.value.children || treeData.value.children.length === 0) return false;

		// 收集所有课程ID
		const allCourseIds : number[] = [];
		treeData.value.children.forEach(section => {
			section.children.forEach(course => {
				allCourseIds.push(course.courseId);
			});
		});

		return hasAllCourses(allCourseIds);
	});

	const getChapter = async (categoryId : any) => {

		try {
			let data = {
				parentCategoryId: categoryId.categoryId - 0
			};
			const res = await getChapterById(data);
			let re = transformToTree(res.data);
			treeData.value = re[0];
			console.log('transformToTree', treeData.value)
		} catch (error) {
			console.log('获取数据失败', error)
		}
	}

	function getCatergin() {
	}

	// 点击支付 
	const handleAlipay = async () => {
		try {
			if (userStore.userInfo.userId == null || userStore.userInfo.userId == undefined) {
				errorMessage.value = '加载支付页面失败';
				return;
			}
			// 生成订单
			let data = {
				userId: userStore.userInfo.userId,
				courseId: '',
				paymentAmount: paymentAmount,
				paymentStatus: "待付款",
				amendName: userStore.userInfo.amendName,
				notes: "",
			}
			const res = await createOrder(data);

		} catch (error) {
			console.log('新增失败', error)
		}
	}

	function toDeatl(item) {
		console.log("点击卡片", item);
		uni.redirectTo({
			url: "/pages/clazz/index?courseId=" + item.courseId + "&title=" + item.title + "&description=" + item.originalData.description,
			fail: (err) => {
				console.log('跳转失败详情:', err);
				uni.showToast({
					title: '跳转失败: ' + err.errMsg,
					icon: 'none'
				});
			},
			success: () => {
				console.log('跳转成功');
			}
		});

	}

	function closeOrder() {
		ifclick.value = false;
	}

	function toOrder(moneny, name, alldata) {
		// 在这里判断如果 没有登录 就去登录页面
		if (userStore.userInfo == "" || userStore.userInfo == null) {
			navigateToLogin('购买需要先返回登录页面');
			return;
		}
		let courseIdzz = [];
		let payment =[];
		if (alldata.key == "all-courses") {
			for (let sitem of alldata.children) {
				for (let item of sitem.children) {
					if (!item.hasnode) {
						courseIdzz.push(item.courseId);
						payment.push(item.price)
					}
				}
			}
		} else {
			for (let item of alldata.children) {
				if (!item.hasnode) {
					courseIdzz.push(item.courseId);
					payment.push(item.price)
				}
			}
		}
		console.log("useUserStore", userStore.userInfo)
		console.log(alldata)
		paymentAmount = moneny;
		// ifclick.value=true;
		pagcontent.value.moneny = moneny;
		pagcontent.value.name = name;
		navigateTo("/pages/orderPage/buynowPage?courseIds=" + courseIdzz.join(",") + "&paymentAmounts=" + payment.join(","));
	}

	function transformToTree(courseData) {
		// 第一层：汇总所有课程
		const rootNode = {
			title: '所有课程',
			key: 'all-courses',
			children: [],
			totalPrice: 0 // 初始化总价格
		};

		// 用对象来暂存阶段分组
		const stageMap = {};

		// 遍历所有课程数据
		courseData.forEach(course => {
			const stageName = course.chapterNames || '未分类阶段';

			// 如果阶段不存在，则创建
			if (!stageMap[stageName]) {
				stageMap[stageName] = {
					title: stageName,
					key: `stage-${stageName}`,
					children: [],
					totalPrice: 0
				};
				rootNode.children.push(stageMap[stageName]);
			}

			// 创建课程节点
			let courseNode = {
				title: `${course.courseName} `,
				key: `course-${course.courseId}`,
				isLeaf: true,
				price: course.price,
				courseId: course.courseId,
				originalData: course,// 保留原始数据
				hasnode: false
			};
			if (userHaveCourseId.value.includes(course.courseId)) {
				courseNode.hasnode = true
			} else {
				courseNode.hasnode = false;
				rootNode.totalPrice += course.price;
			}
			// 添加到对应阶段
			stageMap[stageName].children.push(courseNode);
			stageMap[stageName].totalPrice += course.price;


		});

		// 为每个阶段节点添加价格显示
		rootNode.children.forEach(stage => {
			stage.title = `${stage.title} `;
		});

		// 为根节点添加价格显示
		rootNode.title = `${rootNode.title} (¥${rootNode.totalPrice})`;

		return [rootNode]; // 返回数组形式，符合树形组件通常的预期
	}

	onMounted(() => {
		selectUserHaveCourseId();

		if (uni.getStorageSync('userInfo') != "") {
			userInfo = JSON.parse(uni.getStorageSync('userInfo'));
		}
		userStore.setCatergoryDeatil(category);
		userStore.setClazz(null);
		//在这里加到全局变量
		
	})

	//用来保存从后端 通过userId 查询出来的拥有的courseId
	const userHaveCourseId = ref<number[]>([]);

	//通过userId 查询出来的拥有的courseId方法
	function selectUserHaveCourseId() {
		if (!userStore.getUserId) {
			getChapter(category);
		} else {
			// 发送请求
			uni.request({
				url: 'http://127.0.0.1:8088/course/getMyCourseId',
				method: 'GET',
				data: { userId: userStore.getUserId },
				header: {
					'Content-Type': 'application/json',
				},
				success: (res) => {
					console.log('查询课程ID成功:', res.data);

					if (res.data.code === 200 && Array.isArray(res.data.data)) {
						userHaveCourseId.value = res.data.data;
						getChapter(category);
					} else {
						console.warn('数据格式异常或查询失败', res.data);
						userHaveCourseId.value = [];
					}
				},
				fail: (err) => {
					console.error('查询课程ID失败:', err);
					uni.showToast({
						title: '网络错误，请稍后再试',
						icon: 'none'
					});
				}
			});
		}


	}

	onLoad((options) => {
		category = options;
	})
</script>

<style>
	page {
		height: 100%;
		background-color: #f5f5f5;
	}

	.page {
		display: flex;
		flex-direction: column;
		height: 100%;
	}

	.header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		height: 88rpx;
		padding: 0 32rpx;
		background-color: #ffffff;
		border-bottom: 1px solid #f0f0f0;
	}

	.title {
		font-size: 16px;
		font-weight: 500;
		color: #333333;
	}

	.back-icon,
	.more-icon {
		width: 48rpx;
		height: 48rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.course-overview {
		display: flex;
		padding: 32rpx;
		background-color: #ffffff;
		margin-bottom: 20rpx;
	}

	.overview-left {
		flex: 1;
		margin-right: 32rpx;
	}

	.course-title {
		font-size: 20px;
		font-weight: 600;
		color: #333333;
		margin-bottom: 16rpx;
		display: block;
	}

	.course-desc {
		font-size: 14px;
		color: #666666;
		margin-bottom: 32rpx;
		display: block;
	}

	.price-button {
		background-color: #2979ff;
		border-radius: 8rpx;
		padding: 24rpx 0;
		text-align: center;
		margin: 0 32rpx 20rpx;
	}

	.price-text {
		color: #ffffff;
		font-size: 16px;
		font-weight: 500;
	}

	.price-text.purchased {
		color:  #f5f5f5;
	}

	.overview-right {
		width: 120rpx;
		height: 120rpx;
		flex-shrink: 0;
	}

	.ai-icon {
		width: 100%;
		height: 100%;
		border-radius: 60rpx;
	}

	.course-list {
		flex: 1;
		overflow: auto;
		padding: 0 32rpx;
	}

	.course-section {
		background-color: #ffffff;
		margin-bottom: 20rpx;
		padding: 32rpx;
		border-radius: 12rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.section-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 24rpx;
	}

	.section-title {
		font-size: 16px;
		font-weight: 500;
		color: #333333;
	}

	.section-info {
		font-size: 14px;
		color: #999999;
	}

	.section-price {
		background-color: #f5f7fa;
		padding: 24rpx;
		border-radius: 8rpx;
		margin-bottom: 32rpx;
		transition: all 0.3s;
	}

	.section-price.purchased {
		background-color: #e8f5e9;
	}

	.price-label {
		font-size: 14px;
		color: #666666;
	}

	.course-card {
		display: flex;
		padding: 24rpx 0;
		border-bottom: 1px solid #f0f0f0;
	}

	.course-card:last-child {
		border-bottom: none;
	}

	.card-left {
		width: 96rpx;
		height: 96rpx;
		margin-right: 24rpx;
		flex-shrink: 0;
	}

	.course-icon {
		width: 100%;
		height: 100%;
		border-radius: 16rpx;
	}

	.card-right {
		flex: 1;
	}

	.card-title {
		font-size: 16px;
		color: #333333;
		margin-bottom: 8rpx;
		display: block;
	}

	.card-desc {
		font-size: 14px;
		color: #666666;
		margin-bottom: 16rpx;
		display: block;
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
	}

	.card-stats {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.views {
		display: flex;
		align-items: center;
	}

	.view-count {
		font-size: 12px;
		color: #999999;
		margin-left: 8rpx;
	}

	.course-price {
		font-size: 14px;
		color: #ff6b00;
		font-weight: 500;
	}

	.pay-container {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 999;
	}

	.pay-mask {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.6);
	}

	.pay-content {
		position: relative;
		width: 600rpx;
		background-color: #ffffff;
		border-radius: 24rpx;
		padding: 40rpx;
	}

	.pay-title {
		font-size: 18px;
		color: #333333;
		font-weight: 500;
		text-align: center;
		margin-bottom: 30rpx;
	}

	.pay-notice {
		font-size: 14px;
		color: #666666;
		line-height: 1.4;
		margin-bottom: 40rpx;
	}

	.pay-info {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 40rpx;
	}

	.info-name {
		font-size: 16px;
		color: #333333;
	}

	.info-price {
		font-size: 16px;
		color: #333333;
		font-weight: 500;
	}

	.pay-actions {
		display: flex;
		gap: 20rpx;
		margin-bottom: 30rpx;
	}

	.action-btn {
		flex: 1;
		height: 80rpx;
		line-height: 80rpx;
		font-size: 14px;
		border-radius: 12rpx;
		margin: 0;
	}

	.alipay {
		text-align: center;
		background-color: #1677ff;
		color: #ffffff;
	}

	.wechat {
		background-color: #07c160;
		color: #ffffff;
	}

	.pay-tips {
		font-size: 12px;
		color: #999999;
		line-height: 1.5;
	}
</style>